//
//  FSHomeViewController+BluetoothList.m
//  FSiOSClient
//
//  Created by purlible on 2024/8/23.
//

#import "FSHomeViewController+BluetoothList.h"
#import "FSHomeViewController+BluetoothData.h"

@implementation FSHomeViewController (BluetoothList)

- (void)initTableView
{
    self.peripheralDataArray = [[NSMutableArray alloc]init];
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(25, 150, SCREEN_WIDTH-50, 250) style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.hidden = YES;
    self.table.backgroundColor = [UIColor systemRedColor];
    self.table.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.view addSubview:self.table];
    
    UILabel * headerLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-50, 20)];
    headerLable.text = @"请选择蓝牙设备";
    headerLable.textAlignment = NSTextAlignmentCenter;
    headerLable.font = [UIFont boldSystemFontOfSize:14];
    headerLable.textColor = UIColorHex(0x666666);
    headerLable.backgroundColor = UIColorHex(0x51CDCD);
    self.table.tableHeaderView = headerLable;
    
    self.table.layer.borderColor = UIColorHex(0x666666).CGColor;
    self.table.layer.cornerRadius = 5;
    self.table.layer.borderWidth = 1;
}

#pragma mark -UIViewController 方法
//插入table数据
-(void)insertTableView:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSArray *peripherals = [self.peripheralDataArray valueForKey:@"peripheral"];
    if(![peripherals containsObject:peripheral]) {
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:peripherals.count inSection:0];
        [indexPaths addObject:indexPath];
        
        NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
        [item setValue:peripheral forKey:@"peripheral"];
        [item setValue:RSSI forKey:@"RSSI"];
        [item setValue:advertisementData forKey:@"advertisementData"];
        [item setValue:@"0" forKey:@"status"];
        NSString * code = [NSString stringWithFormat:@"%lu",(unsigned long)self.peripheralDataArray.count];
        [item setValue:code forKey:@"code"];
        [self.peripheralDataArray addObject:item];
        [self.table insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
        [self updateH5BluetoothList];
    }
}

#pragma mark -table委托 table delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.peripheralDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:@"cell"];
    NSDictionary *item = [self.peripheralDataArray objectAtIndex:indexPath.row];
    CBPeripheral *peripheral = [item objectForKey:@"peripheral"];
    NSDictionary *advertisementData = [item objectForKey:@"advertisementData"];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //peripheral的显示名称,优先用kCBAdvDataLocalName的定义，若没有再使用peripheral name
    NSString *peripheralName;
    if ([advertisementData objectForKey:@"kCBAdverDataLocalName"]) {
        peripheralName = [NSString stringWithFormat:@"%@",[advertisementData objectForKey:@"kCBAdvDataLocalName"]];
    }else if(!([peripheral.name isEqualToString:@""] || peripheral.name == nil)){
        peripheralName = peripheral.name;
    }else{
        peripheralName = [peripheral.identifier UUIDString];
    }
    
    cell.textLabel.text = peripheralName;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //停止扫描
    [self.baby cancelScan];
    [self.table deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *item = [self.peripheralDataArray objectAtIndex:indexPath.row];
    CBPeripheral *peripheral = [item objectForKey:@"peripheral"];
    self.currPeripheral = peripheral;
    [self connectBluetooth];
    
    for (NSMutableDictionary *item in self.peripheralDataArray) {
        NSString * code = [item objectForKey:@"code"];
        if ([self.peripheralCode isEqualToString:code]) {
            //更新蓝牙列表
            [item setValue:@"1" forKey:@"status"];
        }else{
            [item setValue:@"0" forKey:@"status"];
        }
    }
    
    [self.table setHidden:YES];
}

#pragma mark -- 更新H5蓝牙列表
- (void)updateH5BluetoothList
{
    NSMutableArray * list = [NSMutableArray array];
    for (int i=0; i<self.peripheralDataArray.count; i++) {
        NSMutableDictionary * blueItem = self.peripheralDataArray[i];
        CBPeripheral * peripheral = [blueItem objectForKey:@"peripheral"];
        NSString * status = [blueItem objectForKey:@"status"];
        NSString * code = [blueItem objectForKey:@"code"];
        //peripheral的显示名称,优先用kCBAdvDataLocalName的定义，若没有再使用peripheral name
        NSString *peripheralName;
        if(!([peripheral.name isEqualToString:@""] || peripheral.name == nil)){
            peripheralName = peripheral.name;
        }
        if (!peripheralName) {
            peripheralName = @"无名称";
        }
        NSString * itemString = [NSString stringWithFormat:@"%@,%@,%@",code,peripheralName,status];
        [list addObject:itemString];
    }

    NSString * jsonListString = [list componentsJoinedByString:@";"];
    NSString *jsString = [NSString stringWithFormat:@"window.getbluetoothlist('%@')",jsonListString];
    [self.webView evaluateJavaScript:jsString completionHandler:nil];
    
    DDLogDebug(@"传蓝牙数组给js:%@",jsonListString);
}


@end
